/* eslint-disable */

import fs from 'fs-extra';
import path, { resolve } from 'path';
import type { ProxyOptions } from 'vite';
import { devDependencies } from '../../package.json';

export interface ViteEnv {
  VITE_USE_MOCK: boolean;
  VITE_USE_PWA: boolean;
  VITE_PUBLIC_PATH: string;
  VITE_PROXY: [string, string][];
  VITE_GLOB_APP_TITLE: string;
  VITE_GLOB_APP_SHORT_NAME: string;
  VITE_USE_CDN: boolean;
  VITE_DROP_CONSOLE: boolean;
  VITE_BUILD_COMPRESS: 'gzip' | 'brotli' | 'none';
  VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE: boolean;
  VITE_LEGACY: boolean;
  VITE_USE_IMAGEMIN: boolean;
  VITE_IS_UNI: boolean;
  VITE_GENERATE_UI: string;
  VITE_USE_MORE_PAGE: string;
  VITE_VUE_REACTIVITY_TRANSFORM: boolean;
  VITE_AUTO_OPEN: boolean;
  VITE_OPEN_VCONSOLE: boolean;
  
  VITE_BUILD_MATCH_FILE: string;
  VITE_BUILD_IGNORE_MATCH_FILE: string;
  VITE_BUILD_PREFIX_NAME: string;
  VITE_DEV_DEFAULT_PAGE?: string;
  VITE_PAGEJUMP_TYPE?: '_self' | '_blank';
  VITE_USE_HTTPS?: boolean;
  VITE_OPEN_TS_CHECK?: boolean;
  VITE_PROJECT_TYPE?: 'app' | 'web';
  VITE_REM_ROOT_VALUE?: number;
}

export function wrapperEnv (envConf: Record<string, any>): ViteEnv {
  const viteEnv: Partial<ViteEnv> = {};
  
  for (const key of Object.keys(envConf)) {
    let realName = envConf[key].replace(/\\n/g, '\n');
    realName = realName === 'true' ? true : realName === 'false' ? false : realName;
    
    if (key === 'VITE_PROXY' && realName) {
      try {
        realName = JSON.parse(realName.replace(/'/g, '"'));
      } catch (error) {
        realName = '';
      }
    }
    
    viteEnv[key] = realName;
    if (typeof realName === 'string') {
      process.env[key] = realName;
    } else if (typeof realName === 'object') {
      process.env[key] = JSON.stringify(realName);
    }
  }
  return viteEnv as ViteEnv;
}

export function resolveProxy (proxyList: [string, string][] = []) {
  const proxy: Record<string, ProxyOptions> = {};
  for (const [prefix, target] of proxyList) {
    const isHttps = /^https:\/\//.test(target);
    
    proxy[prefix] = {
      target: target,
      changeOrigin: true,
      ws: true,
      rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
      
      ...(isHttps ? { secure: false } : {})
    };
  }
  return proxy;
}

export function resolveProxyHttp2 (proxyList: [string, string][] = []) {
  const proxy: Record<string, ProxyOptions> = {};
  for (const [prefix, target] of proxyList) {
    const isHttps = /^https:\/\//.test(target);
    
    proxy[prefix] = {
      target: target,
      
      rewrite: (path) => path.replace(new RegExp(`^${prefix}`), '')
      
    };
  }
  return proxy;
}

export function createDir (targetDir) {
  if (!fs.existsSync(targetDir)) {
    fs.mkdirsSync(targetDir);
  }
}

export function soloveVueTstError (root) {
  const viteVersion = devDependencies.vite.replace('^', '');
  const vitePluginCheckerVersion = devDependencies['vite-plugin-checker'].replace('^', '');
  
  const _vitePluginPath = path.join(root, '/configs/vite/node_modules/vite-plugin-checker/lib/checkers/vueTsc/typescript-vue-tsc');
  
  if (fs.existsSync(_vitePluginPath) && !fs.existsSync(_vitePluginPath + '/package.json')) {
    fs.copyFileSync(path.join(root, '/configs/vite/src/utils/vue-tsc-error'), _vitePluginPath + '/package.json');
  }
}

export function getOptimizeDepIncludes (isAdmin, isMorePage) {
  let optimizeDepInclude = ['vue', '@vueuse/core', 'lodash-es', 'axios', 'qs', 'dayjs', 'pinia', 'vue-router', 'element-plus/es', 'vue-request'];
  optimizeDepInclude = optimizeDepInclude.concat(['pinia', 'vue-router']);
  return optimizeDepInclude;
}

export function generateModifyVars (isAdmin: string | undefined) {
  const primary = '#2a7dc9';
  
  const proName = isAdmin ? 'web' : 'app';
  
  return {
    hack: `true; @import (reference) "${resolve(`./node_modules/@vc/styles/vars/${proName}/index.less`)}";`
  };
}

export function getProRootPath (root: string, projectDirName: string) {
  projectDirName = '/' + projectDirName + '/';
  const rootSplit = root.split(projectDirName);
  rootSplit.pop();
  return rootSplit.join(projectDirName);
}
